/**
 * 资料列表
 */
package com.xiaomuwu.android.ui.shared

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.xiaomuwu.android.MainActivity
import com.xiaomuwu.android.R
import com.xiaomuwu.android.XiaoMuWuApplication
import com.xiaomuwu.android.logic.model.ForReleRes
import com.xiaomuwu.android.logic.model.ForRes
import com.xiaomuwu.android.ui.Displayer
import com.xiaomuwu.android.ui.ForSearch
import com.xiaomuwu.android.ui.home.ResViewModel
import com.xiaomuwu.android.ui.LoginStatus
import com.xiaomuwu.android.ui.detail.ResDetailFragment
import com.xiaomuwu.android.ui.rele.ReleResViewModel
import com.xiaomuwu.android.ui.upload.UploadResFragment
import kotlinx.android.synthetic.main.res_list_fragment.*

class ResListFragment:Fragment() {

    private val releResViewModel by lazy{ ViewModelProviders.of(this).get(
        ReleResViewModel::class.java)}

    private val resViewModel by lazy{ ViewModelProviders.of(this).get(
        ResViewModel::class.java)}

    private lateinit var adapter: ResListAdapter

    private lateinit var updateResReceiver: UpdateResReceiver   // 刷新资料列表广播接收器
    private lateinit var updateReleResReceiver: UpdateReleResReceiver   // 刷新相关资料列表广播接收器
    private lateinit var showResDetailReceiver: ShowResDetailReceiver   // 显示资料详情广播接收器

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.res_list_fragment,container,false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        // 设置广播过滤器并注册广播接收器
        updateResReceiver=UpdateResReceiver()
        val updateResFilter=IntentFilter()
        updateResFilter.addAction("com.xiaomuwu.android.UpdateRes")
        XiaoMuWuApplication.context.registerReceiver(updateResReceiver,updateResFilter)

        updateReleResReceiver=UpdateReleResReceiver()
        val updateReleResFilter=IntentFilter()
        updateReleResFilter.addAction("com.xiaomuwu.android.UpdateReleRes")
        XiaoMuWuApplication.context.registerReceiver(updateReleResReceiver,updateReleResFilter)

        showResDetailReceiver = ShowResDetailReceiver()
        val showResDetailFilter = IntentFilter()
        showResDetailFilter.addAction("com.xiaomuwu.android.ShowResDetail")
        XiaoMuWuApplication.context.registerReceiver(showResDetailReceiver,showResDetailFilter)

        val layoutManager= LinearLayoutManager(activity)
        resListRecyclerView?.layoutManager=layoutManager

        // 根据页面设置资料查询监听
        if(Displayer.pageStatus=="Home") {
            adapter= ResListAdapter(resViewModel.resList)
            resListRecyclerView?.adapter=adapter
            resViewModel.resLiveData.observe(viewLifecycleOwner, { result->
                val res=result.getOrNull()
                if (res!=null) {
                    resViewModel.resList.clear()
                    resViewModel.resList.addAll(res)
                    adapter.notifyDataSetChanged()
                    Log.d("ResListFragment","Res查询成功")
                }else {
                    Log.d("ResListFragment","Res查询失败")
                }
                scrollToBrowse()    // 滚动到浏览位置
            })
            resViewModel.getResLiveData(ForRes(ForSearch.contentName,ForSearch.forResTags,
                ForSearch.resSortBy))   // 刷新资料列表
        }else if(Displayer.pageStatus =="Favorites" || Displayer.pageStatus =="Upload") {
            adapter= ResListAdapter(releResViewModel.releResList)
            resListRecyclerView?.adapter=adapter
            releResViewModel.releResLiveData.observe(viewLifecycleOwner, { result->
                val res=result.getOrNull()
                if (res!=null){
                    releResViewModel.releResList.clear()
                    releResViewModel.releResList.addAll(res)
                    adapter.notifyDataSetChanged()
                    Log.d("ResListFragment","ReleRes查询成功")
                }else{
                    Log.d("ResListFragment","ReleRes查询失败")
                }
                scrollToBrowse()    // 滚动到浏览位置
            })
            releResViewModel.getReleResLiveData(ForReleRes(LoginStatus.user_ID!!,
                ForSearch.contentName)) // 刷新相关资料列表
        }

        // “上传” 按钮点击监听
        uploadButton.setOnClickListener {
            if(LoginStatus.user_ID == null) {
                Toast.makeText(XiaoMuWuApplication.context,"请先登录",
                    Toast.LENGTH_SHORT).show()
            }else {
                // 切换至上传页
                if(activity != null) {
                    val mainActivity = activity as MainActivity
                    Displayer.pprevPageStatus = Displayer.prevPageStatus
                    Displayer.prevPageStatus = Displayer.pageStatus
                    Displayer.pageStatus = "UploadRes"
                    mainActivity.replaceFragment(UploadResFragment())
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        // 取消注册广播接收器
        XiaoMuWuApplication.context.unregisterReceiver(updateResReceiver)
        XiaoMuWuApplication.context.unregisterReceiver(updateReleResReceiver)
        XiaoMuWuApplication.context.unregisterReceiver(showResDetailReceiver)
    }

    /**
     * 滚动到浏览位置函数
     */
    private fun scrollToBrowse() {
        // 定位浏览位置
        val range=0 until resViewModel.resList.size
        if(Displayer.resPosition!=0) {
            for(position in range) {
                if(resViewModel.resList[position].id==ForSearch.resID) {
                    Displayer.resPosition=position
                    break
                }
            }
        }

        try {
            resListRecyclerView?.scrollToPosition(Displayer.resPosition)    // 滚动
            Displayer.resPosition=0 // 重置浏览位置
            Log.d("ResListFragment","滚动成功")
        }catch (e:Exception) {
            e.printStackTrace()
            Log.d("ResListFragment","滚动失败")
        }
    }

    /**
     * 刷新资料列表广播接收器
     */
    inner class UpdateResReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            // 更新资料列表
            resViewModel.getResLiveData(
                ForRes(ForSearch.contentName,ForSearch.forResTags, ForSearch.resSortBy)
            )
        }
    }

    /**
     * 刷新相关资料列表广播接收器
     */
    inner class UpdateReleResReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            // 更新相关资料列表
            releResViewModel.getReleResLiveData(
                ForReleRes(LoginStatus.user_ID!!,ForSearch.contentName)
            )
        }
    }

    /**
     * 显示资料详情广播接收器
     */
    inner class ShowResDetailReceiver:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            // 切换至资料详情页
            if (activity != null) {
                val mainActivity = activity as MainActivity
                mainActivity.hideKeyboard() // 收起键盘
                mainActivity.replaceFragment(ResDetailFragment())
            }
        }
    }

}